package com.etong.frame.directive.impl.database;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.etong.frame.directive.Directive;
import com.etong.frame.directive.DirectiveConfig;
import com.etong.frame.directive.checker.CheckerGroup;
import com.etong.frame.directive.factory.DirectiveFactory;
import com.etong.frame.directive.mybatis.DirectiveStatementMapper;

public class DirectiveFactoryImpl implements DirectiveFactory {
	protected static final Logger logger = LoggerFactory
			.getLogger(DirectiveFactoryImpl.class);

	private DirectiveExecutorImpl executor = new DirectiveExecutorImpl();

	public DatabaseDirective createDirective(Statement statement) {

		String tableOp = statement.getTable_op();
		DatabaseDirective directive = null;
		if (DatabaseDirective.SELECT.equalsIgnoreCase(tableOp)) {
			directive = new DatabaseSelect(statement);
		} else if (DatabaseDirective.UPDATE.equalsIgnoreCase(tableOp)) {
			directive = new DatabaseUpdate(statement);
		} else if (DatabaseDirective.INSERT.equalsIgnoreCase(tableOp)) {
			directive = new DatabaseInsert(statement);
		} else if (DatabaseDirective.DELETE.equalsIgnoreCase(tableOp)) {
			directive = new DatabaseDelete(statement);
		} else if (DatabaseDirective.REPLACE.equalsIgnoreCase(tableOp)) {
			directive = new DatabaseReplace(statement);
		} else if (DatabaseDirective.COUNT.equalsIgnoreCase(tableOp)) {
			directive = new DatabaseCount(statement);
		} else {
			directive = new DatabaseDefault(statement);
		}

		// 初始化指令
		if (!directive.initDirective()) {
			logger.error("Init directive failed:" + statement);
			return null;
		}

		// 给指令设置执行器
		directive.setExecutor(executor);

		return directive;
	}

	@Override
	public Directive createDirective(DirectiveConfig directiveConfig,
			CheckerGroup checkerGroup) {
		Statement statement = (Statement) directiveConfig;
		DatabaseDirective directive = createDirective(statement);
		directive.setCheckerGroup(checkerGroup);
		return directive;
	}

	public void setDirectiveMapper(DirectiveStatementMapper mapper) {
		// 创建执行器
		executor.setDirectiveMapper(mapper);
	}
}
